package com.me.hippy.sdk.demo.chat

import android.app.Activity
import android.content.res.Resources
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver

class KeyboardHelper private constructor(
    private val listenView: View,
    private val keyboardChangeListener: (isShowed: Boolean, keyboardHeight: Int) -> Unit
) : ViewTreeObserver.OnGlobalLayoutListener {
    companion object {
        fun listen(
            activity: Activity,
            keyboardChangeListener: (isShowed: Boolean, keyboardHeight: Int) -> Unit
        ): KeyboardHelper {
            return KeyboardHelper(activity.window.decorView, keyboardChangeListener)
        }
    }

    private var currentKeyboardHeight = -1
    private val visibleDisplayFrame = Rect()

    init {
        listenView.viewTreeObserver.addOnGlobalLayoutListener(this)
    }

    private fun getNavigationBarHeight(): Int {
        val system = Resources.getSystem()
        val identifier = system.getIdentifier("navigation_bar_height", "dimen", "android")
        return if (identifier != 0) {
            system.getDimensionPixelSize(identifier)
        } else 0
    }

    override fun onGlobalLayout() {
        listenView.getWindowVisibleDisplayFrame(visibleDisplayFrame)
//            val height = visibleDisplayFrame.height()
        val keyboardHeight = listenView.height - visibleDisplayFrame.bottom
        if (currentKeyboardHeight != keyboardHeight) {
            keyboardChangeListener.invoke(
                keyboardHeight - getNavigationBarHeight() > 0,
                if (keyboardHeight > 0) keyboardHeight else 0
            )
            currentKeyboardHeight = keyboardHeight
        }
    }
}